<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon running">
              <el-icon><VideoPlay /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ runningTasks }}</div>
              <div class="stats-label">运行中任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon stopped">
              <el-icon><VideoPause /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stoppedTasks }}</div>
              <div class="stats-label">已停止任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon error">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ errorTasks }}</div>
              <div class="stats-label">错误任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon total">
              <el-icon><List /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalTasks }}</div>
              <div class="stats-label">总任务数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 任务管理表单 -->
    <el-card class="task-form-card">
      <template #header>
        <div class="card-header">
          <span>任务管理</span>
          <el-button type="primary" @click="showCronHelper = true">
            <el-icon><QuestionFilled /></el-icon>
            Cron表达式帮助
          </el-button>
        </div>
      </template>
      
      <el-form :model="taskForm" :rules="rules" ref="taskFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Cron表达式" prop="cronExpression">
              <el-input 
                v-model="taskForm.cronExpression" 
                placeholder="例如: 0/15 * * * * ?"
                clearable
              >
                <!-- 删除右侧帮助按钮 -->
                <!-- <template #append>
                  <el-button @click="showCronHelper = true">帮助</el-button>
                </template> -->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input 
                v-model="taskForm.serviceName" 
                placeholder="例如: taskTestServiceImpl"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="方法名称" prop="serviceMethod">
              <el-input 
                v-model="taskForm.serviceMethod" 
                placeholder="例如: testPrint1"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="startTask" :loading="startLoading">
                <el-icon><VideoPlay /></el-icon>
                启动任务
              </el-button>
              <el-button type="danger" @click="stopTask" :loading="stopLoading" style="margin-left: 10px;">
                <el-icon><VideoPause /></el-icon>
                停止任务
              </el-button>
              <el-button @click="resetForm" style="margin-left: 10px;">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="task-list-card">
      <template #header>
        <div class="card-header">
          <span>当前任务</span>
          <el-button type="primary" @click="refreshTaskList">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <el-table :data="taskList" stripe v-loading="tableLoading" empty-text="暂无任务">
        <el-table-column prop="serviceName" label="服务名称" min-width="150"></el-table-column>
        <el-table-column prop="serviceMethod" label="方法名称" min-width="120"></el-table-column>
        <el-table-column prop="cronExpression" label="Cron表达式" min-width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="启动时间" width="180"></el-table-column>
        <el-table-column prop="lastExecuteTime" label="最后执行" width="180"></el-table-column>
        <el-table-column prop="nextExecuteTime" label="下次执行" width="180"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleStopTask(scope.row)"
              :disabled="scope.row.status === 'stopped'"
            >
              停止
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleStartTask(scope.row)"
              :disabled="scope.row.status === 'running'"
              style="margin-left: 5px;"
            >
              启动
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Cron表达式帮助对话框 -->
    <el-dialog v-model="showCronHelper" title="Cron表达式帮助" width="700px">
      <el-tabs v-model="cronTab">
        <el-tab-pane label="常用示例/格式说明" name="help">
          <div class="cron-helper">
            <h4>常用Cron表达式示例：</h4>
            <el-table :data="cronExamples" border>
              <el-table-column prop="expression" label="表达式" width="150"></el-table-column>
              <el-table-column prop="description" label="说明"></el-table-column>
            </el-table>
            <h4 style="margin-top: 20px;">Cron表达式格式：</h4>
            <p><code>秒 分 时 日 月 周</code></p>
            <ul>
              <li><strong>秒</strong>：0-59</li>
              <li><strong>分</strong>：0-59</li>
              <li><strong>时</strong>：0-23</li>
              <li><strong>日</strong>：1-31</li>
              <li><strong>月</strong>：1-12</li>
              <li><strong>周</strong>：1-7 或 SUN-SAT</li>
            </ul>
            <h4>特殊字符：</h4>
            <ul>
              <li><strong>*</strong>：表示任意值</li>
              <li><strong>?</strong>：表示不指定值（仅用于日和周）</li>
              <li><strong>/</strong>：表示间隔</li>
              <li><strong>-</strong>：表示范围</li>
              <li><strong>,</strong>：表示多个值</li>
            </ul>
          </div>
        </el-tab-pane>
        <el-tab-pane label="专业Cron生成器" name="progen">
          <el-form :model="proForm" label-width="120px" style="max-width: 600px;">
            <el-form-item label="类型">
              <el-select v-model="proForm.type" style="width: 200px;">
                <el-option label="每天" value="day" />
                <el-option label="每周" value="week" />
                <el-option label="每月" value="month" />
                <el-option label="每年" value="year" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间点">
              <el-time-picker
                v-model="proForm.times"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                style="width: 300px;"
              />
            </el-form-item>
            <el-form-item v-if="proForm.type === 'week'" label="星期几">
              <el-checkbox-group v-model="proForm.weekdays">
                <el-checkbox v-for="w in weekdays" :key="w.value" :label="w.value">{{ w.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="proForm.type === 'month'" label="几号">
              <el-select v-model="proForm.daysOfMonth" multiple placeholder="选择日期" style="width: 300px;">
                <el-option v-for="d in 31" :key="d" :label="d+'号'" :value="d" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="proForm.type === 'year'" label="月份">
              <el-select v-model="proForm.months" multiple placeholder="选择月份" style="width: 200px;">
                <el-option v-for="m in 12" :key="m" :label="m+'月'" :value="m" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="proForm.type === 'year'" label="几号">
              <el-select v-model="proForm.daysOfMonth" multiple placeholder="选择日期" style="width: 200px;">
                <el-option v-for="d in 31" :key="d" :label="d+'号'" :value="d" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="proForm.type === 'custom'" label="自定义表达式">
              <el-input v-model="proForm.custom" placeholder="完整Cron表达式" />
            </el-form-item>
          </el-form>
          <div style="margin-top: 20px;">
            <el-input v-model="proCron" readonly placeholder="生成的Cron表达式" style="width: 400px;">
              <template #append>
                <el-button @click="copyProCron" :disabled="!proCron">复制</el-button>
              </template>
            </el-input>
          </div>
          <div v-if="proCopySuccess" style="color: #67c23a; margin-top: 10px;">已复制到剪贴板！</div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  VideoPlay, VideoPause, Warning, List, QuestionFilled, Refresh 
} from '@element-plus/icons-vue'
import { taskApi } from '../api/taskApi'
// import { useTaskStore } from '../stores/taskStore'
import type { TaskRequest, StopTaskRequest, TaskInfo } from '../types/task'

const taskFormRef = ref()
const startLoading = ref(false)
const stopLoading = ref(false)
const tableLoading = ref(false)
const showCronHelper = ref(false)

const taskForm = reactive<TaskRequest>({
  cronExpression: '',
  serviceName: '',
  serviceMethod: ''
})

// 任务列表和分页
const taskList = ref<TaskInfo[]>([])
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)

// 统计数据
const runningTasks = computed(() => taskList.value.filter(t => t.status === 1).length)
const stoppedTasks = computed(() => taskList.value.filter(t => t.status === 0).length)
const errorTasks = computed(() => 0) // 暂无错误状态
const totalTasks = computed(() => taskList.value.length)

// 获取任务列表
const getTaskList = async () => {
  try {
    tableLoading.value = true
    const res = await taskApi.getTaskList({ pageNo: pageNo.value, pageSize: pageSize.value })
    if (res.data.code === 200 && res.data.data) {
      taskList.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      taskList.value = []
      total.value = 0
      ElMessage.error(res.data.msg || '获取任务列表失败')
    }
  } catch (e) {
    taskList.value = []
    total.value = 0
    ElMessage.error('获取任务列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 页面加载时获取任务列表
onMounted(() => {
  getTaskList()
})

const rules = {
  cronExpression: [
    { required: true, message: '请输入Cron表达式', trigger: 'blur' },
    { 
      pattern: /^[0-9*?/]+\s+[0-9*?/]+\s+[0-9*?/]+\s+[0-9*?/LW]+\s+[0-9*?/]+\s+[0-9*?/L#]+$/,
      message: 'Cron表达式格式错误，正确格式: 秒 分 时 日 月 周',
      trigger: 'blur'
    }
  ],
  serviceName: [
    { required: true, message: '服务名称不能为空', trigger: 'blur' },
    { pattern: /^[a-z][a-zA-Z0-9]*$/, message: '服务名称必须为小驼峰格式', trigger: 'blur' }
  ],
  serviceMethod: [
    { required: true, message: '方法名称不能为空', trigger: 'blur' },
    { pattern: /^[a-z][a-zA-Z0-9]*$/, message: '方法名称必须为小驼峰格式', trigger: 'blur' }
  ]
}

const cronExamples = [
  { expression: '0/15 * * * * ?', description: '每15秒执行一次' },
  { expression: '0 0/5 * * * ?', description: '每5分钟执行一次' },
  { expression: '0 0 * * * ?', description: '每小时执行一次' },
  { expression: '0 0 0 * * ?', description: '每天0点执行一次' },
  { expression: '0 0 12 * * ?', description: '每天12点执行一次' },
  { expression: '0 0 0 1 * ?', description: '每月1号0点执行一次' },
  { expression: '0 0 0 ? * MON', description: '每周一0点执行一次' }
]

// 方法
const getStatusType = (status: number) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'info'
    case 2: return 'danger' // 假设2是错误状态
    default: return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '运行中'
    case 0: return '已停止'
    case 2: return '错误'
    default: return '未知'
  }
}

// 启动/停止任务后刷新列表
const startTask = async () => {
  if (!taskFormRef.value) return
  try {
    await taskFormRef.value.validate()
    startLoading.value = true
    const response = await taskApi.startTask(taskForm)
    if (response.data.code === 200) {
      ElMessage.success(response.data.data || response.data.msg)
      await getTaskList()
      resetForm()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.msg || error.message || '启动任务失败')
  } finally {
    startLoading.value = false
  }
}

const stopTask = async () => {
  if (!taskFormRef.value) return
  try {
    await taskFormRef.value.validateField(['serviceName', 'serviceMethod'])
    stopLoading.value = true
    const response = await taskApi.stopTask({
      serviceName: taskForm.serviceName,
      serviceMethod: taskForm.serviceMethod
    })
    if (response.data.code === 200) {
      ElMessage.success(response.data.data || response.data.msg)
      await getTaskList()
      resetForm()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.msg || '停止任务失败')
  } finally {
    stopLoading.value = false
  }
}

const handleStopTask = async (task: TaskInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要停止任务 ${task.serviceName}.${task.serviceMethod} 吗？`,
      '确认停止',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await taskApi.stopTask({
      serviceName: task.serviceName,
      serviceMethod: task.serviceMethod
    })
    if (response.data.code === 200) {
      ElMessage.success(response.data.data || response.data.msg)
      await getTaskList()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '停止任务失败')
    }
  }
}

const handleStartTask = async (task: TaskInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要启动任务 ${task.serviceName}.${task.serviceMethod} 吗？`,
      '确认启动',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    const response = await taskApi.startTask({
      cronExpression: task.cronExpression,
      serviceName: task.serviceName,
      serviceMethod: task.serviceMethod
    })
    if (response.data.code === 200) {
      ElMessage.success(response.data.data || response.data.msg)
      await getTaskList()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '启动任务失败')
    }
  }
}

const refreshTaskList = async () => {
  try {
    tableLoading.value = true
    // 由于后端没有提供获取任务列表的API，这里暂时不调用
    // 任务列表由本地状态管理维护
    console.log('当前任务列表:', taskList.value)
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    tableLoading.value = false
  }
}

const resetForm = () => {
  if (taskFormRef.value) {
    taskFormRef.value.resetFields()
  }
}

// 生命周期
// onMounted(() => {
//   refreshTaskList()
// })

const cronTab = ref('help')

// 专业Cron生成器Tab
const weekdays = [
  { label: '周日', value: '1' },
  { label: '周一', value: '2' },
  { label: '周二', value: '3' },
  { label: '周三', value: '4' },
  { label: '周四', value: '5' },
  { label: '周五', value: '6' },
  { label: '周六', value: '7' }
]
const proForm = reactive({
  type: 'day',
  times: '', // [start, end] HH:mm:ss
  weekdays: [], // ['1','3']
  daysOfMonth: [], // [1,15]
  months: [], // [1,6,12]
  custom: ''
})
const proCron = computed(() => {
  // 解析时间
  let s = '0', m = '*', h = '*'
  if (proForm.times && Array.isArray(proForm.times)) {
    // 取开始时间
    const [start] = proForm.times
    if (start) {
      [h, m, s] = start.split(':')
    }
  } else if (typeof proForm.times === 'string' && proForm.times) {
    [h, m, s] = proForm.times.split(':')
  }
  if (!s) s = '0'; if (!m) m = '0'; if (!h) h = '0';
  if (proForm.type === 'day') {
    return `${s} ${m} ${h} * * ?`
  } else if (proForm.type === 'week') {
    const week = proForm.weekdays.length ? proForm.weekdays.join(',') : '*'
    return `${s} ${m} ${h} ? * ${week}`
  } else if (proForm.type === 'month') {
    const days = proForm.daysOfMonth.length ? proForm.daysOfMonth.join(',') : '1'
    return `${s} ${m} ${h} ${days} * ?`
  } else if (proForm.type === 'year') {
    const months = proForm.months.length ? proForm.months.join(',') : '1'
    const days = proForm.daysOfMonth.length ? proForm.daysOfMonth.join(',') : '1'
    return `${s} ${m} ${h} ${days} ${months} ?`
  } else if (proForm.type === 'custom') {
    return proForm.custom
  }
  return ''
})
const proCopySuccess = ref(false)
const copyProCron = async () => {
  if (!proCron.value) return
  try {
    await navigator.clipboard.writeText(proCron.value)
    proCopySuccess.value = true
    setTimeout(() => { proCopySuccess.value = false }, 1500)
  } catch {
    ElMessage.error('复制失败，请手动复制')
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stats-icon.running {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stats-icon.stopped {
  background: linear-gradient(135deg, #909399, #c0c4cc);
}

.stats-icon.error {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stats-icon.total {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.task-form-card,
.task-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cron-helper {
  max-height: 400px;
  overflow-y: auto;
}

.cron-helper h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.cron-helper ul {
  margin: 10px 0;
  padding-left: 20px;
}

.cron-helper li {
  margin: 5px 0;
}

.cron-helper code {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}
</style>